from maix import image, display, app, time, camera
import cv2
import numpy as np

disp = display.Display()
cam = camera.Camera(320, 240, image.Format.FMT_BGR888)

prev_frame = None  # 上一个帧

while not app.need_exit():
    current_frame = cam.read()

    # convert maix.image.Image object to numpy.ndarray object
    # t = time.ticks_ms()
    current_frame_cv = image.image2cv(current_frame, ensure_bgr=False, copy=False)
    # print("time: ", time.ticks_ms() - t)

    if prev_frame is not None:
        # 计算帧差
        frame_diff = cv2.absdiff(prev_frame, current_frame_cv)
        # 高斯模糊
        frame_diff = cv2.GaussianBlur(frame_diff, (3, 3), 0)
        # 二值化处理
        _, binary_frame = cv2.threshold(cv2.cvtColor(frame_diff, cv2.COLOR_BGR2GRAY), 50, 255, cv2.THRESH_BINARY)
        # 形态学操作：膨胀和腐蚀
        kernel = np.ones((5, 5), np.uint8)
        binary_frame = cv2.dilate(binary_frame, kernel, iterations=1)
        binary_frame = cv2.erode(binary_frame, kernel, iterations=1)
        # 轮廓检测
        contours, _ = cv2.findContours(binary_frame, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
        # 绘制轮廓
        for i, contour in enumerate(contours):
            if cv2.contourArea(contour) > 1 and cv2.contourArea(contour) < 100:  # 筛选激光点
                # 为每个轮廓分配不同的颜色
                color = (np.random.randint(0, 255), np.random.randint(0, 255), np.random.randint(0, 255))
                # 绘制轮廓
                cv2.drawContours(current_frame_cv, [contour], -1, color, 2)
                # 获取轮廓的边界框并绘制矩形框
                x, y, w, h = cv2.boundingRect(contour)
                cv2.rectangle(current_frame_cv, (x, y), (x + w, y + h), color, 2)
                print("x:",x,"y:",y)
    # canny method
    edged = cv2.Canny(current_frame_cv, 180, 60)

    # show by maix.display
    img_show = image.cv2image(current_frame_cv, bgr=True, copy=False)
    disp.show(img_show)

    prev_frame = current_frame_cv  # 更新前一帧
